package util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

/**
 * Jackson util
 *
 * 1、obj 需要有私有属性和对应的 set/get 方法；
 * 2、不支持内部类；
 *
 * @author xxx
 */
@Slf4j
public class JacksonUtil {
    private final static ObjectMapper objectMapper = new ObjectMapper();

    public static ObjectMapper getInstance() {
        return objectMapper;
    }

    /**
     * bean、array、List、Map --> json
     *
     * @param obj
     * @return json 字符串
     * @throws Exception
     */
    public static String toStr(Object obj) throws JsonProcessingException {
        return getInstance().writeValueAsString(obj);
    }

    public static String toFormatStr(Object object) throws JsonProcessingException {
        // 创建 ObjectMapper 对象
        ObjectMapper mapper = getInstance();
        // 将 JSON 字符串解析为 Java 对象
        //Object obj = mapper.readValue(Object, Object.class);
        // 使用默认的 PrettyPrinter 格式化输出 JSON 字符串
        String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);

        return prettyJson;
    }

    /**
     * string --> bean、Map、List(array)
     *
     * @return obj
     */
    public static <T> T readValue(String jsonStr, Class<T> clazz) throws JsonProcessingException {
        return getInstance().readValue(jsonStr, clazz);
    }

    /**
     * string --> List<Bean>...
     *
     * @return
     */
    public static <T> T readValue(String jsonStr, Class<?> parametrized, Class<?>... parameterClasses) throws JsonProcessingException {
        JavaType javaType = getInstance().getTypeFactory().constructParametricType(parametrized, parameterClasses);
        return getInstance().readValue(jsonStr, javaType);
    }
}
